print("dofile:kaiguan.lua")
--use sjson
_G.cjson = sjson
--modify DEVICEID INPUTID APIKEY
DEVICEID = "17866"
APIKEY = "d9e85f947"
INPUTID = "36"
host = host or "www.bigiot.net"
port = port or 8181
LOT = 3
--LED = 4
isConnect = false
gpio.mode(LOT, gpio.OUTPUT)
--gpio.mode(LED,gpio.OUTPUT)
-- close ar first  
gpio.write(LOT, gpio.HIGH)
local timer = tmr.create()
local function run()
  print("run:\n")
  local cu = net.createConnection(net.TCP)
  cu:connect(port, host)
  ok, s = pcall(cjson.encode, {M="checkin",ID=DEVICEID,K=APIKEY})
  if ok then
    print("ok:\n")
    print(s)
  else
    print("failed to encode!")
  end
  if isConnect then
    print("isConnect:\n")
    cu:send(s.."\n")
  end
  -- receive
  cu:on("receive", function(cu, c) 
    print("receive:")
    print(c)
    isConnect = true
    r = cjson.decode(c)
    if r.M == "checkinok" then   
--        gpio.write(LOT, gpio.LOW)
    end
    if r.M == "say" then
      if r.C == "play" then   
        gpio.write(LOT, gpio.LOW)
--        gpio.write(LED, gpio.LOW)  
        ok, played = pcall(cjson.encode, {M="say",ID=r.ID,C="LED turn on!"})
        cu:send( played.."\n" )
      end
      if r.C == "stop" then   
        gpio.write(LOT, gpio.HIGH)
--        gpio.write(LED, gpio.HIGH)
        ok, stoped = pcall(cjson.encode, {M="say",ID=r.ID,C="LED turn off!"})
        cu:send( stoped.."\n" ) 
      end
    
    end
  end)
  cu:on('disconnection',function(scu)
    print("disconnection:")
    print(scu)
--    gpio.write(LOT, gpio.HIGH)
    cu = nil
    isConnect = false
    timer:stop(1)
    timer:alarm(5000, tmr.ALARM_AUTO, run)
  end)


  -- ping
  timer:alarm(30000, tmr.ALARM_AUTO, function()
    if isConnect then
      print("ping:\n")
      cu:send(s.."\n")
    end
  end)
  
end
run()
